package com.jb.repair.dao;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.jb.repair.F1Application;
import com.jb.repair.common.AppConfig;
import com.jb.repair.common.Constants;
import com.jb.repair.model.DeviceModel;
import com.jb.repair.model.ItemModel;
import com.jb.repair.model.PositionModel;
import com.jb.repair.model.QxjlModel;
import com.jb.repair.model.TaskModel;
import com.jb.repair.model.YcjlModel;
import com.jb.repair.util.StringUtils;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by gaobin on 2015/11/7.
 */
public class QueryDb {
    private final String TASK_TABLE_NAME = "TB_SI_TASK";    //点检任务表名
    private final String TASK_RESULT_TABLE_NAME = "TB_SI_TASK_RESULT";    //点检任务结果表表名

    private String TAG = "Querydb";
    private static SQLiteDatabase db;
    private static QueryDb mydb;

    private String userName;
    private String userId;
    SharedPreferences sp;

    private QueryDb(Context context) {
        sp = F1Application.getAppConext().getSharedPreferences(Constants.SP_NAME, Context.MODE_PRIVATE);
        db = context.getApplicationContext().openOrCreateDatabase(AppConfig.DB_PATh, Context.MODE_PRIVATE, null);
    }

    public static synchronized QueryDb getInstance(Context context) {
        if (mydb == null)
            mydb = new QueryDb(context);
        return mydb;
    }

    public List<TaskModel> getAllTask() {
        String sql = "SELECT GUID from " + TASK_TABLE_NAME;
        //  Log.i(TAG,sql);
        Cursor c = db.rawQuery(sql, null);
        List<TaskModel> list = new ArrayList<TaskModel>();
        while (c.moveToNext()) {
            TaskModel model = new TaskModel();
            model.guid = c.getString(c.getColumnIndex("GUID"));
            list.add(model);
        }
        return list;
    }

    public int getTaskInplaceRate(String taskId){
        int result = 0;



        return result;
    }

    /**
     * 获取用户历史任务列表
     * @return
     */
    public List<TaskModel> getHisTask(Boolean isB) {
        userId = sp.getString(Constants.PERSON_GUID, "");
        userName = sp.getString(Constants.PERSON_NAME, "");
        List<TaskModel> list = new ArrayList<TaskModel>();
        String name = userName;
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        String sql;

        // 只显示最近3天的任务（之前2天+今天）
        Date sevenDaysAgo = new Date(curDate.getTime() - 2 * 24 * 60 * 60 * 1000);
        String seven = "'" + formatter.format(sevenDaysAgo) + " 00:00:00'";


        sql = "SELECT * from " + TASK_TABLE_NAME + " where si_person_a_id='" + userId + "' and del_mark!='T' and task_date >= " + seven + " order by task_date desc";

        //  Log.i(TAG,sql);
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            String taskDate = c.getString(c.getColumnIndex("task_date")).substring(0, 10);
            try {
                calendar.setTime(formatter.parse(taskDate));
                Long taskTime = calendar.getTimeInMillis();
                calendar.setTime(formatter.parse(str));
                Long nowTime = calendar.getTimeInMillis();
                if (taskTime < nowTime) {
                    TaskModel model = new TaskModel();
                    model.guid = c.getString(c.getColumnIndex("GUID"));
                    model.plan_id = c.getString(c.getColumnIndex("plan_id"));
                    model.si_new_person_a = name;
                    model.task = c.getString(c.getColumnIndex("task"));
                    model.task_date = c.getString(c.getColumnIndex("task_date"));
                    model.abnormal_num = getTaskAbnormalNum(model.guid);
                    Integer[] aa = getTaskMustCheckedItemNum(model.guid);
                    model.total_si_num = aa[0];
                    model.total_unsi_num = aa[1];
                    int a = (model.total_unsi_num + model.total_si_num);
                    if (a == 0)
                        model.inPlaceRate = "100";
                    else {
                        float d = (float) (model.total_si_num * 100) / (float) a;
                        DecimalFormat format = new DecimalFormat("#0.0");
                        model.inPlaceRate = format.format(d);
                    }
                    list.add(model);
                    if (list.size() >= 7) {
                        return list;
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        c.close();
        if (isB) {
            sql = "SELECT * from " + TASK_TABLE_NAME + " where si_person_b_id='" + userId + "' and del_mark!='T' order by task_date desc";
            //  Log.i(TAG,sql);
            Cursor c1 = db.rawQuery(sql, null);
            while (c1.moveToNext()) {
                String taskDate = c1.getString(c.getColumnIndex("task_date")).substring(0, 10);
                try {
                    calendar.setTime(formatter.parse(taskDate));
                    Long taskTime = calendar.getTimeInMillis();
                    calendar.setTime(formatter.parse(str));
                    Long nowTime = calendar.getTimeInMillis();
                    if (taskTime < nowTime) {
                        TaskModel model = new TaskModel();
                        model.guid = c1.getString(c.getColumnIndex("GUID"));
                        model.plan_id = c1.getString(c1.getColumnIndex("plan_id"));
                        model.si_new_person_a = name;
                        model.task = c1.getString(c1.getColumnIndex("task")) + "(B角)";
                        model.task_date = c1.getString(c.getColumnIndex("task_date"));
                        model.abnormal_num = getTaskAbnormalNum(model.guid);
                        model.total_si_num = getTaskCheckedItemNum(model.guid)[0];
                        model.total_unsi_num = getTaskCheckedItemNum(model.guid)[1];
                        int a = (model.total_unsi_num + model.total_si_num);
                        if (a == 0)
                            model.inPlaceRate = "100";
                        else {
                            float d = (float) (model.total_si_num * 100) / (float) a;
                            DecimalFormat format = new DecimalFormat("#0.0");
                            model.inPlaceRate = format.format(d);
                        }
                        list.add(model);
                        if (list.size() > 7)
                            return list;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            c1.close();
        }
        return list;
    }

    /**
     * 获取用户今日任务列表
     *
     * @return
     */
    public List<TaskModel>  getTodayTask(Boolean hasB) {
        userId = sp.getString(Constants.PERSON_GUID, "");
        userName = sp.getString(Constants.PERSON_NAME, "");
        List<TaskModel> list = new ArrayList<TaskModel>();
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String sql = "SELECT * from " + TASK_TABLE_NAME + " where si_person_a_id='" + userId + "'" + " and task_date LIKE " + "'" + date + "%' and del_mark!='T' order by task_date desc";
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            TaskModel model = new TaskModel();
            model.guid = c.getString(c.getColumnIndex("GUID"));
            model.plan_id = c.getString(c.getColumnIndex("plan_id"));
            model.task = c.getString(c.getColumnIndex("task"));
            model.task_status = c.getString(c.getColumnIndex("task_status"));
            model.task_date = c.getString(c.getColumnIndex("task_date"));
            model.si_person_a = userName;
            String b_name = c.getString(c.getColumnIndex("si_person_b"));
            model.si_person_b = userName == b_name ? c.getString(c.getColumnIndex("si_person_a")) : b_name;
            model.total_pos_num = getTaskTotalPosNum(model.guid);
            model.total_si_num = getTaskCheckedItemNum(model.guid)[0];
            model.total_unsi_num = getTaskCheckedItemNum(model.guid)[1];
            if (model.total_unsi_num == 0) {
                ContentValues cv = new ContentValues();
                cv.put("task_status", "已完成");
                db.update("TB_SI_TASK", cv, "GUID=?", new String[]{model.guid});
                model.task_status = "已完成";
            }
            model.abnormal_num = getTaskAbnormalNum(model.guid);
            model.total_dev_num = getTaskTotalDevNum(model.guid);
            list.add(model);
            model.isB = false;
        }
        if (hasB) {
            String sql1 = "SELECT * from " + TASK_TABLE_NAME + " where si_person_b_id='" + userId + "'" + " and task_date LIKE " + "'" + date + "%' and del_mark!='T' order by task_date desc";
            //  Log.i(TAG + "abc", sql1);
            Cursor c1 = db.rawQuery(sql1, null);
            while (c1.moveToNext()) {
                TaskModel model = new TaskModel();
                model.guid = c1.getString(c.getColumnIndex("GUID"));
                model.plan_id = c1.getString(c.getColumnIndex("plan_id"));
                model.task = c1.getString(c.getColumnIndex("task"));
                model.task_status = "未完成";
                model.task_date = c1.getString(c.getColumnIndex("task_date"));
                model.si_person_a = userName;
                String b_name = c1.getString(c.getColumnIndex("si_person_b"));
                model.si_person_b = userName == b_name ? c1.getString(c.getColumnIndex("si_person_a")) : b_name;
                model.total_pos_num = getTaskTotalPosNum(model.guid);
                model.total_si_num = getTaskCheckedItemNum(model.guid)[0];
                model.total_unsi_num = getTaskCheckedItemNum(model.guid)[1];
                model.abnormal_num = getTaskAbnormalNum(model.guid);
                model.total_dev_num = getTaskTotalDevNum(model.guid);
                if (model.total_unsi_num == 0) {
                    ContentValues cv = new ContentValues();
                    cv.put("task_status", "已完成");
                    db.update("TB_SI_TASK", cv, "GUID=?", new String[]{model.guid});
                    model.task_status = "已完成";
                }
                model.isB = true;
                list.add(model);
            }
            c1.close();
        }
        c.close();
        return list;
    }

    /**
     * 根据任务id获取该任务的位置总数
     *
     * @param taskId 任务id
     * @return 项目总数
     */
    public int getTaskTotalPosNum(String taskId) {
        int num = 0;
        String sql = "select count(distinct place_id) from TB_SI_TASK_RESULT where task_id ='" + taskId + "'";
        Log.i(TAG, sql);
        Cursor c = db.rawQuery(sql, null);
        if (c.moveToNext()) {
            num = c.getInt(0);
        }
        c.close();
        return num;
    }

    public int getTaskTotalDevNum(String taskId) {
        int num = 0;
        String sql = "select count(distinct dev_id) from TB_SI_TASK_RESULT where task_id ='" + taskId + "'";
        Log.i(TAG, sql);
        Cursor c = db.rawQuery(sql, null);
        if (c.moveToNext()) {
            num = c.getInt(0);
        }
        c.close();
        return num;
    }


    /**
     * 根据任务id获取该任务已点检项目数和待点检项目数
     *
     * @param taskId
     * @return
     */
    public Integer[] getTaskCheckedItemNum(String taskId) {
        int checkednum = 0;
        int uncheckednum = 0;
        String sql = "SELECT si_person from " + TASK_RESULT_TABLE_NAME + " where task_id='" + taskId + "'";
        Log.i(TAG, sql);
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            String name = c.getString(0);
            if (name != null && !name.equals(""))
                checkednum++;
            else
                uncheckednum++;
        }
        c.close();
        Integer[] result = new Integer[]{checkednum, uncheckednum};
        return result;
    }

    public Integer[] getTaskMustCheckedItemNum(String taskId) {
        int checkednum = 0;
        int uncheckednum = 0;
        String sql = "SELECT si_person from " + TASK_RESULT_TABLE_NAME + " where task_id='" + taskId + "' and is_must_today='T'";
        Log.i(TAG, sql);
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            String name = c.getString(0);
            if (name != null && !name.equals(""))
                checkednum++;
            else
                uncheckednum++;
        }
        c.close();
        Integer[] result = new Integer[]{checkednum, uncheckednum};
        return result;
    }

    /**
     * 根据任务id获取该任务已异常项目数
     *
     * @param taskId
     * @return
     */
    public int getTaskAbnormalNum(String taskId) {
        int num = 0;
        String sql = "SELECT count(*) from " + TASK_RESULT_TABLE_NAME + " where task_id='" + taskId + "' and (is_abnormal='T' or is_defect='T') and si_person!=''";
        Cursor c = db.rawQuery(sql, null);
        if (c.moveToFirst())
            num = c.getInt(0);
        c.close();
//        while (c.moveToNext()) {
//            String isAbnormal = c.getString(0);
//            if (isAbnormal != null && isAbnormal.equals("T"))
//                num++;
//        }
//        String sql2 = "SELECT is_defect from " + TASK_RESULT_TABLE_NAME + " where task_id='" + taskId + "'";
//        Log.i(TAG, sql);
//        Cursor c2 = db.rawQuery(sql2, null);
//        while (c2.moveToNext()) {
//            String isAbnormal = c2.getString(0);
//            if (isAbnormal != null && isAbnormal.equals("T"))
//                num++;
//        }
        return num;
    }

    /**
     * 获取某个任务的位置列表
     *
     * @param taskId
     * @return
     */
    public List<PositionModel> getPositionList(String taskId) {
        List<PositionModel> list = new ArrayList<PositionModel>();
        String sql = "select distinct place_id,place from tb_si_task_result where task_id='" + taskId + "'";
        Cursor c = db.rawQuery(sql, null);

        while (c.moveToNext()) {
            PositionModel model = new PositionModel();
            model.id = c.getString(c.getColumnIndex("place_id"));
            model.ins_position_name = c.getString(c.getColumnIndex("place"));
            model.dev_num_today = getPosTotalDevNum(model.id, taskId);
            model.item_num_today = getPosTotalItemNum(model.id, taskId);
            model.dev_checked_num = getPosCheckedItemNum(model.id, taskId);
            model.item_abnormal_num = getPosAbnormalItemNum(model.id, taskId);
            list.add(model);
        }
        c.close();
        return list;
    }

    /**
     * 获取指定位置今天点检设备数
     *
     * @return
     */
    public int getPosTotalDevNum(String placeId, String taskId) {
        int result = 0;
        String sql = "SELECT COUNT(DISTINCT dev_id) from tb_si_task_result where task_id='" + taskId + "' and place_id='" + placeId + "' and dev_id!=''";
        //Log.i(TAG, sql);
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext())
            result = c.getInt(0);
        c.close();
        return result;
    }

    /**
     * 获取指定位置点检项目总数
     *
     * @param placeId
     * @return
     */
    public int getPosTotalItemNum(String placeId, String taskId) {
        int result = 0;
        String sql = "select count(0) from tb_si_task_result where task_id='" + taskId + "' and place_id='" + placeId + "'";
        // Log.i(TAG,sql);
        Cursor c = db.rawQuery(sql, null);
        c.moveToNext();
        result = c.getInt(0);
        c.close();
        return result;
    }

    /**
     * 获取指定位置已点检项目数
     *
     * @return
     */
    public int getPosCheckedItemNum(String placeId, String taskId) {
        int result = 0;
        String sql = "select count(0) from tb_si_task_result where task_id='" + taskId + "' and place_id='" + placeId + "' and si_person_id!=''";
        Cursor c = db.rawQuery(sql, null);
        c.moveToNext();
        result = c.getInt(0);
        c.close();

        return result;
    }

    /**
     * 获取指定位置异常项目数
     *
     * @param placeId
     * @return
     */
    public int getPosAbnormalItemNum(String placeId, String taskId) {
        int result = 0;
        String sql = "select count(0) from tb_si_task_result where (task_id='" + taskId + "' and place_id='" + placeId + "' and si_person_id!='') and (is_abnormal='T' or is_defect='T')";
        Cursor c = db.rawQuery(sql, null);
        c.moveToNext();
        result = c.getInt(0);
        c.close();

        return result;
    }


    public List<String> getAllEqName(String taskId, String placeId) {
        List<String> list = new ArrayList<>();
        String sql = "SELECT DISTINCT dev_name from tb_si_task_result where place_id='" + placeId + "' and task_id='" + taskId + "' order by dev_id";
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            String name = c.getString(0).equals("") ? "环境类" : c.getString(0);
            list.add(name);
        }
        c.close();
        return list;
    }

    public DeviceModel getPosDeviceModel(String taskId, String placeId, int flag, int start) {
        String sql = "SELECT DISTINCT dev_id,dev_name from tb_si_task_result where place_id='" + placeId + "' and task_id='" + taskId + "' order by dev_id";
        Cursor c = db.rawQuery(sql, null);
        DeviceModel model = new DeviceModel();
        if (c.moveToPosition(start)) {
            model.equipName = c.getString(1).equals("") ? "环境类" : c.getString(1);
            model.id = c.getString(0);
            Map<Integer, List<ItemModel>> map = new HashMap<>();
            map = getAllDevItem(placeId, taskId, model.id, flag);
            model.todayCheckList = map.get(1);
            model.weekCheckList = map.get(2);
            model.monthCheckList = map.get(3);
            model.twiceWeekCheckList = map.get(4);
            model.thirdWeekCheckList = map.get(5);
            model.twiceMonthCheckList = map.get(6);
            c.close();
            if (model.todayCheckList.size() == 0 && model.weekCheckList.size() == 0 && model.monthCheckList.size() == 0
                    && model.twiceWeekCheckList.size() == 0 && model.thirdWeekCheckList.size() == 0 && model.twiceMonthCheckList.size() == 0) {
                return null;
            }
            return model;
        }
        c.close();
        return null;
    }

    public DeviceModel getPosDeviceModelPre(String taskId, String placeId, int flag, int start) {
        String sql = "SELECT DISTINCT dev_id,dev_name from tb_si_task_result where place_id='" + placeId + "' and task_id='" + taskId + "' order by dev_id";
        if (start == 0) {
            return null;
        }
        Cursor c = db.rawQuery(sql, null);
        DeviceModel model = new DeviceModel();
        if (c.moveToPosition(start - 1)) {
            model.equipName = c.getString(1).equals("") ? "环境类" : c.getString(1);
            model.id = c.getString(0);
            Map<Integer, List<ItemModel>> map = new HashMap<>();
            map = getAllDevItem(placeId, taskId, model.id, flag);
            model.todayCheckList = map.get(1);
            model.weekCheckList = map.get(2);
            model.monthCheckList = map.get(3);
            model.twiceWeekCheckList = map.get(4);
            model.thirdWeekCheckList = map.get(5);
            model.twiceMonthCheckList = map.get(6);
            c.close();
            return model;
        }
        c.close();
        return null;
    }

    public int getDeviceNum(String taskId, String placeId) {
        List<DeviceModel> list = new ArrayList<>();
        String sql = "SELECT DISTINCT dev_id,dev_name from tb_si_task_result where place_id='" + placeId + "' and task_id='" + taskId + "' order by dev_id";
        Cursor c = db.rawQuery(sql, null);
        int count = c.getCount();
        c.close();
        return count;
    }

    public List<DeviceModel> getAllNumDeviceModel(String taskId, String placeId) {
        List<DeviceModel> list = new ArrayList<>();
        String sql = "SELECT DISTINCT dev_id,dev_name from tb_si_task_result where place_id='" + placeId + "' and task_id='" + taskId + "' order by dev_id";
//        Log.i(TAG, "getAllNumDeviceModel sql:" + sql);
        Cursor c = db.rawQuery(sql, null);
        int i = 0;
        while (c.moveToNext()) {
//            Log.i(TAG,"index=" + i++);
            DeviceModel model = new DeviceModel();
            model.id = c.getString(0);
            Map<Integer, List<ItemModel>> map = new HashMap<>();
            map = getAllDevItem(placeId, taskId, model.id, 2);
            model.equipName = c.getString(1).equals("") ? "环境类" : c.getString(1);

            model.todayCheckList = map.get(1);
            model.weekCheckList = map.get(2);
            model.monthCheckList = map.get(3);
            model.twiceWeekCheckList = map.get(4);
            model.thirdWeekCheckList = map.get(5);
            model.twiceMonthCheckList = map.get(6);
            if (model.todayCheckList.size() == 0 && model.weekCheckList.size() == 0 && model.monthCheckList.size() == 0
                    && model.twiceWeekCheckList.size() == 0 && model.thirdWeekCheckList.size() == 0 && model.twiceMonthCheckList.size() == 0) {
                continue;
            } else {
                Log.i(TAG, "equipName = " + model.equipName);
                list.add(model);

            }

        }
        c.close();
        return list;
    }

    public List<DeviceModel> getPosDeviceModelForLoc(String taskId, String placeId, int flag, int loc) {
        List<DeviceModel> list = new ArrayList<DeviceModel>();
        String sql = "SELECT DISTINCT dev_id,dev_name from tb_si_task_result where place_id='" + placeId + "' and task_id='" + taskId + "' order by dev_id";
        Cursor c = db.rawQuery(sql, null);
        if (loc == 0)
            c.moveToPosition(loc - 1);
        else
            c.moveToPosition(loc - 2);
        while (c.moveToNext()) {
            DeviceModel model = new DeviceModel();
            model.equipName = c.getString(1).equals("") ? "环境类" : c.getString(1);
            model.id = c.getString(0);
            Map<Integer, List<ItemModel>> map = new HashMap<>();
            map = getAllDevItem(placeId, taskId, model.id, flag);
            model.todayCheckList = map.get(1);
            model.weekCheckList = map.get(2);
            model.monthCheckList = map.get(3);
            model.twiceWeekCheckList = map.get(4);
            model.thirdWeekCheckList = map.get(5);
            model.twiceMonthCheckList = map.get(6);
            list.add(model);
            if (list.size() > 2) {
                c.close();
                return list;
            }
        }
        c.close();
        return list;
    }

    public Map<Integer, List<ItemModel>> getAllDevItem(String placeId, String taskId, String devId, int m) {
        Map<Integer, List<ItemModel>> map = new HashMap<Integer, List<ItemModel>>();
        List<ItemModel> dayItemList = new ArrayList<>();
        List<ItemModel> weekItemList = new ArrayList<>();
        List<ItemModel> monthItemList = new ArrayList<>();
        List<ItemModel> twiceweekItemList = new ArrayList<>();
        List<ItemModel> thirdweekList = new ArrayList<>();
        List<ItemModel> twicemonthList = new ArrayList<>();

        String sql = "SELECT * from " + TASK_RESULT_TABLE_NAME + " where dev_id='" + devId + "' and task_id='" + taskId + "' and place_id='" + placeId + "'";

        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            ItemModel model = new ItemModel();
            model.method = c.getString(c.getColumnIndex("method"));
            //过滤
            if ((m == 1 && "0401902".equals(model.method)) || (m == 2 && "0401901".equals(model.method))) {
                continue;
            }

            model.planId = c.getString(c.getColumnIndex("plan_id"));
            model.resultId = c.getString(c.getColumnIndex("GUID")); // to do
            model.position = c.getString(c.getColumnIndex("position"));
            model.content = c.getString(c.getColumnIndex("content"));
            model.standard = c.getString(c.getColumnIndex("standard"));
            String ismust = c.getString(c.getColumnIndex("is_must_today"));
            model.isMust = "T".equals(ismust);
            model.preCheckDate = getPreCheckTime(model.planId);
            model.unit = c.getString(c.getColumnIndex("unit"));
            model.tools = c.getString(c.getColumnIndex("tools"));
            model.standard_min = c.getString(c.getColumnIndex("standard_min"));
            model.standard_max = c.getString(c.getColumnIndex("standard_max"));

            model.num_result = c.getInt(c.getColumnIndex("num_result"));
            model.desc_result = c.getString(c.getColumnIndex("desc_result"));
            model.checkPerson = c.getString(c.getColumnIndex("si_person"));
            model.isAbnormal = "T".equals(c.getString(c.getColumnIndex("is_abnormal"))) || "T".equals(c.getString(c.getColumnIndex("is_defect")));
            model.cycle = c.getString(c.getColumnIndex("cycle"));
            model.dev_id = c.getString(c.getColumnIndex("dev_id"));
         //   Log.i("gaobin","最大值1：" + model.standard_max + "最小值1：" + model.standard_min + "点检值1："  + model.num_result);
            if (StringUtils.isBlank(model.checkPerson)) {
                if (m == 1) {
                    model.checkResult = "正常";
                } else if (m == 2) {
                    model.checkResult = "";
                } else {
                    model.checkResult = "未检查";
                }
            } else if ("0401902".equals(model.method)) { // 数值类数据
                // 单位替换，model.unit为单位代号，转换后为真正的单位
                model.checkResult = model.num_result + transformUnit(model.unit);
            } else if (!model.isAbnormal) {
                model.checkResult = "正常";
            } else {
                model.checkResult = "异常";
            }

            //批量处理中观察类默认点检结果为正常，数值类默认点检结果为空白

            if (model.cycle.equals("0401606")) {
                dayItemList.add(model);
            } else if (model.cycle.equals("0401609")) {
                weekItemList.add(model);
            } else if (model.cycle.equals("0401608")) {
                monthItemList.add(model);
            } else if (model.cycle.equals("0401610")) {
                twiceweekItemList.add(model);
            } else if (model.cycle.equals("0401607")) {
                thirdweekList.add(model);
            } else if (model.cycle.equals("0401611")) {
                twicemonthList.add(model);
            }
        }
        c.close();
        map.put(1, dayItemList);
        map.put(2, weekItemList);
        map.put(3, monthItemList);
        map.put(4, twiceweekItemList);
        map.put(5, thirdweekList);
        map.put(6, twicemonthList);
        return map;
    }

    /**
     * 单位换算
     *
     * @param unit {String} 单位代号
     * @return 代号对应的单位
     */
    private String transformUnit(String unit) {
        // 摄氏度
        if ("0406701".equals(unit)) return "℃";
        // 千克
        if ("0406702".equals(unit)) return "KG";
        // 其他情况，单位为空
        return "";
    }

    public String getPreCheckTime(String itemId) {
        String result = "";
        String sql = "select si_time from TB_SI_TASK_RESULT where si_time!='' and plan_task_detail_id='" + itemId + "'order by si_time desc";
        Cursor c = db.rawQuery(sql, null);
        if (c.moveToFirst()) {
            result = c.getString(0);
        }
        c.close();
        return result;
    }

    //获得用户的所有异常
    public List<YcjlModel> getAllAbnormal(String taskId) {
        List<YcjlModel> list = new ArrayList<>();
        String sql = "select * from TB_SI_TASK_RESULT where task_id='" + taskId + "' and is_abnormal='T' and abnormal_desc!=''";
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            YcjlModel model = new YcjlModel();
            model.result_id = c.getString(c.getColumnIndex("GUID"));
            String planId = c.getString(c.getColumnIndex("plan_task_detail_id"));
            model.eq_name = this.getName("dev_name", "TB_SI_TASK_RESULT", "GUID", planId);
            model.found_time = c.getString(c.getColumnIndex("si_time"));
            model.abn_describe = c.getString(c.getColumnIndex("abnormal_desc"));
            model.attachment = c.getString(c.getColumnIndex("attachment"));
            // TODO: 2016/1/5 点检结果表中无处理方式，但点检管理页面需要展示处理方式
            // model.dealtype_id = c.getString(c.getColumnIndex("dealtype_id"));
            list.add(model);
        }
        c.close();
        return list;
    }

    public List<QxjlModel> getAllDefect(String taskId) {
        List<QxjlModel> list = new ArrayList<>();

        String sql = "select * from TB_SI_TASK_RESULT where task_id='" + taskId + "' and is_defect='T'";
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            QxjlModel model = new QxjlModel();
            //  model.guid = c.getString(c.getColumnIndex("guid"));
            //   model.layer_code = c.getString(c.getColumnIndex("layer_code"));
            //  model.attacheq_id = c.getString(c.getColumnIndex("attacheq_id"));
            //  model.source_guid = c.getString(c.getColumnIndex("eq_id"));
            // model.source_id = c.getString(c.getColumnIndex("source_id"));
            model.result_id = c.getString(c.getColumnIndex("GUID"));
            String planId = c.getString(c.getColumnIndex("plan_task_detail_id"));
            model.eq_name = this.getName("dev_name", "TB_SI_TASK_RESULT", "GUID", planId);
            model.defect_describe = c.getString(c.getColumnIndex("defect_desc"));
            model.level_id = c.getString(c.getColumnIndex("defect_level_id"));
            model.found_time = c.getString(c.getColumnIndex("si_time"));
            model.type_id = c.getString(c.getColumnIndex("defect_type_guid"));
            // model.foundman_id = c.getString(c.getColumnIndex("foundman_id"));
            model.attachment = c.getString(c.getColumnIndex("attachment"));
            list.add(model);
        }
        c.close();
        return list;
    }

    //用于表之间的关联
    public String getName(String aim, String table, String key, String value) {
        Cursor c = db.rawQuery("SELECT * from " + table + " where " + key + " = '" + value + "'", null);
        if (c.moveToNext()) {
            String string = c.getString(c.getColumnIndex(aim));
            c.close();
            return string;
        }
        c.close();
        return "";
    }

    //获取批量处理权限
    public Boolean getAuthority() {
        String sql = "select volume_set_app from TB_SI_SETTING where person_guid='" + F1Application.getUserId() + "'";
        Cursor c = db.rawQuery(sql, null);
        if (c.moveToNext()) {
            String authority = c.getString(0);
            if ("T".equals(authority)) {
                c.close();
                return true;
            }
        }
        c.close();
        return false;
    }

    public YcjlModel getAbnormalByResultId(String resultId) {
        YcjlModel model = new YcjlModel();
        String sql = "select * from TB_EQ_ABNORMAL where inspect_id='" + resultId + "'";
        Cursor c = db.rawQuery(sql, null);
        if (c.moveToFirst()) {
            model.result_id = c.getString(c.getColumnIndex("inspect_id"));
            model.abn_describe = c.getString(c.getColumnIndex("abn_describe"));
            model.attachment = c.getString(c.getColumnIndex("attachment"));
        }
        c.close();
        return model;
    }

    public QxjlModel getDefectByResultId(String resultId) {
        QxjlModel model = new QxjlModel();
        String sql = "select * from TB_EQ_DEFECT where inspect_id='" + resultId + "'";
        Cursor c = db.rawQuery(sql, null);
        if (c.moveToFirst()) {
            model.defect_describe = c.getString(c.getColumnIndex("defect_describe"));
            model.attachment = c.getString(c.getColumnIndex("attachment"));
        }
        c.close();
        return model;
    }

    public String getResentTaskTime(String userId) {
        String time = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        String sql = "SELECT task_date from " + TASK_TABLE_NAME + " where si_person_a_id='" + userId + "'" + " order by task_date desc";
        Cursor c = db.rawQuery(sql, null);
        if (c.moveToNext()){
            time = c.getString(0);
        }
        return time;
    }

}